package cn.jdemo.juc.future.FutureTask;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * // 获取任务执行结果，如果任务没有执行完成，调用次方法线程会一直阻塞，知道任务完成
 * V get()
 * // 和上面一样功能，不同的是多了阻塞时间限制，在限制时间内没有完成则抛出异常
 * public V get(long timeout, TimeUnit unit)
 * // 获取任务执行状态，执行完成返回true
 * public boolean isDone()
 * // 获取任务的取消状态，如果任务完成前被取消，则返回true
 * public boolean isCancelled()
 * // 取消任务执行
 * public boolean cancel(boolean mayInterruptIfRunning)
 * @description
 * @date 2020/12/3
 */
public class FutureTaskDemo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test0();
        test1();
    }

    /**
     * (1) 直接构建FutureTask对象
     * (2) 线程消费FutureTask对象
     */
    public static void test0() throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<String>(() -> {
            System.out.print("当前线程: "+Thread.currentThread().getName() +" ");
            return "abc";
        });
        new Thread(futureTask).start();// FutureTask -- 对runnable + future 进一步实现包装

        String s = futureTask.get();// 异步阻塞
        System.out.println(s);
    }

    /**
     * (1) Executors构建Callable对象
     * (2) FutureTask封装Callable对象
     * (3) 线程消费FutureTask对象
     */
    public static void test1() throws ExecutionException, InterruptedException {
        Callable<String> xyz = Executors.callable(() -> {
            System.out.print("当前线程: "+Thread.currentThread().getName() +" ");
        }, "xyz");
        FutureTask<String> futureTask = new FutureTask<>(xyz);
        new Thread(futureTask).start();

        String s = futureTask.get();
        System.out.println(s);
    }
}
